<template>
  <div class="publish-book">
    <NavBar />
    <main class="container">
      <h1>{{ pageTitle }}</h1>
      <p class="subtitle">填写以下信息，让其他同学了解你的书籍</p>
      
      <LoadingSpinner v-if="isLoading" message="加载数据中..." />
      
      <form v-else class="publish-form" @submit.prevent="submitForm">
        <div class="form-section">
          <h2>基本信息</h2>
          
          <div class="form-group">
            <label for="title">书名 <span class="required">*</span></label>
            <input 
              type="text" 
              id="title" 
              v-model="form.title" 
              required 
              placeholder="请输入书籍的完整名称"
            >
          </div>
          
          <div class="form-group">
            <label for="author">作者 <span class="required">*</span></label>
            <input 
              type="text" 
              id="author" 
              v-model="form.author" 
              required 
              placeholder="请输入作者姓名"
            >
          </div>
          
          <div class="form-group">
            <label for="category">分类 <span class="required">*</span></label>
            <select id="category" v-model="form.categoryId" required>
              <option value="" disabled>请选择书籍分类</option>
              <option v-for="category in categories" :key="category.id" :value="category.id">
                {{ category.name }}
              </option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="price">价格 (元) <span class="required">*</span></label>
            <input 
              type="number" 
              id="price" 
              v-model.number="form.price" 
              required 
              min="1" 
              step="0.1" 
              placeholder="请输入价格"
            >
          </div>
        </div>
        
        <div class="form-section">
          <h2>书籍状态</h2>
          
          <div class="form-group">
            <label>新旧程度 <span class="required">*</span></label>
            <div class="condition-slider">
              <input 
                type="range" 
                v-model.number="form.newDegree" 
                min="1" 
                max="10" 
                step="1"
              >
              <div class="slider-labels">
                <span>旧</span>
                <span>{{ getConditionText(form.newDegree) }}</span>
                <span>新</span>
              </div>
            </div>
          </div>
          
          <div class="form-group">
            <label for="description">书籍描述 <span class="required">*</span></label>
            <textarea 
              id="description" 
              v-model="form.description" 
              required 
              rows="5" 
              placeholder="请详细描述书籍的情况，例如有无笔记、破损等情况"
            ></textarea>
          </div>
        </div>
        
        <div class="form-section">
          <h2>上传图片</h2>
          
          <div class="form-group">
            <label>书籍照片 <span class="required">*</span></label>
            <div class="upload-area" @click="triggerFileInput">
              <input 
                type="file" 
                ref="fileInput" 
                @change="handleFileUpload" 
                accept="image/*" 
                style="display: none"
              >
              <div v-if="!form.cover" class="upload-placeholder">
                <i class="upload-icon">+</i>
                <p>点击上传封面图片</p>
                <p class="upload-hint">支持 JPG、PNG 格式，不超过 5MB</p>
              </div>
              <div v-else class="preview-container">
                <img :src="previewImage" alt="书籍封面预览" class="image-preview">
                <button type="button" class="remove-image" @click.stop="removeImage">删除</button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- <div class="form-section">
          <h2>联系方式</h2>
          
          <div class="form-group">
            <label for="phone">手机号码</label>
            <input 
              type="tel" 
              id="phone" 
              v-model="form.sellerPhone" 
              placeholder="请输入手机号码（选填）"
              pattern="[0-9]{11}"
            >
          </div>
          
          <div class="form-group">
            <label for="wechat">微信</label>
            <input 
              type="text" 
              id="wechat" 
              v-model="form.sellerWechat" 
              placeholder="请输入微信号（选填）"
            >
          </div>
          
          <div class="form-group">
            <label for="department">所在学院</label>
            <input 
              type="text" 
              id="department" 
              v-model="form.sellerDepartment" 
              placeholder="请输入所在学院（选填）"
            >
          </div>
        </div> -->
        
        <div class="form-actions">
          <button type="button" class="btn-cancel" @click="cancelPublish">取消</button>
          <button type="submit" class="btn-submit" :disabled="isSubmitting">
            {{ submitButtonText }}
          </button>
        </div>
      </form>
    </main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import NavBar from '../components/NavBar.vue'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import api from '@/api/apiClient'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const fileInput = ref(null)
const previewImage = ref('')
const isSubmitting = ref(false)
const isLoading = ref(true)
const categories = ref([])
const isEditMode = computed(() => !!route.params.id)
const bookId = computed(() => route.params.id)
const pageTitle = computed(() => isEditMode.value ? '编辑书籍' : '发布二手书')
const submitButtonText = computed(() => isEditMode.value ? (isSubmitting.value ? '保存中...' : '保存修改') : (isSubmitting.value ? '发布中...' : '发布书籍'))

const form = reactive({
  title: '',
  author: '',
  categoryId: '',
  price: '',
  newDegree: 7, // 默认7成新
  description: '',
  cover: null,
  sellerPhone: '',
  sellerWechat: '',
  sellerDepartment: ''
})

// 获取书籍分类
const fetchCategories = async () => {
  try {
    const response = await api.category.getAll()
    console.log('获取分类列表成功:', response)
    
    if (Array.isArray(response)) {
      categories.value = response
    } else if (response && response.data && Array.isArray(response.data)) {
      categories.value = response.data
    } else {
      console.error('获取分类失败: 返回格式不正确', response)
      categories.value = []
    }
  } catch (error) {
    console.error('获取分类失败:', error)
    ElMessage.error('获取分类失败')
    categories.value = []
  }
}

// 获取书籍详情
const fetchBookDetails = async () => {
  if (!isEditMode.value) return
  
  try {
    const response = await api.book.getDetail(bookId.value)
    console.log('获取书籍详情成功:', response)
    
    let bookData = null
    if (response && response.code === 200 && response.data) {
      bookData = response.data
    } else if (response && response.id) {
      bookData = response
    }
    
    if (bookData) {
      // 填充表单数据
      form.title = bookData.title || ''
      form.author = bookData.author || ''
      form.price = bookData.price || ''
      form.description = bookData.description || ''
      
      // 设置新旧程度，将百分比转换为1-10
      form.newDegree = bookData.new_degree ? Math.round(bookData.new_degree / 10) : 7
      
      // 设置分类ID
      if (bookData.category) {
        const category = categories.value.find(c => c.name === bookData.category)
        if (category) {
          form.categoryId = category.id
        }
      }
      
      // 如果有封面，需要加载预览图
      if (bookData.cover === true) {
        try {
          const coverResponse = await api.book.getCover(bookId.value)
          if (coverResponse && typeof coverResponse === 'string') {
            // 设置预览图，但不设置 form.cover，因为在编辑模式下不需要重新上传封面
            previewImage.value = `http://localhost:8080/${coverResponse}`
          }
        } catch (error) {
          console.error('获取书籍封面失败:', error)
        }
      } else if (typeof bookData.cover === 'string') {
        // 如果封面是字符串路径，直接使用
        previewImage.value = `http://localhost:8080/${bookData.cover}`
      }
    }
  } catch (error) {
    console.error('获取书籍详情失败:', error)
    ElMessage.error('获取书籍详情失败')
  }
}

onMounted(async () => {
  isLoading.value = true
  try {
    await fetchCategories()
    if (isEditMode.value) {
      await fetchBookDetails()
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，请刷新页面重试')
  } finally {
    isLoading.value = false
  }
})

const getConditionText = (newDegree) => {
  if (newDegree >= 9) return '全新'
  if (newDegree >= 7) return '良好'
  if (newDegree >= 5) return '一般'
  return '较旧'
}

const getBookCondition = (newDegree) => {
  if (newDegree >= 9) return 'new'
  if (newDegree >= 7) return 'good'
  if (newDegree >= 5) return 'used'
  return 'poor'
}

const triggerFileInput = () => {
  fileInput.value.click()
}

const handleFileUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 检查文件大小（5MB）
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过5MB')
      return
    }
    
    form.cover = file
    previewImage.value = URL.createObjectURL(file)
  }
}

const removeImage = () => {
  form.cover = null
  previewImage.value = ''
  // 重置file input
  fileInput.value.value = ''
}

// 在script setup部分添加一个新函数，用于预加载图片
const preloadImage = (url) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      console.log('封面图片预加载成功:', url);
      resolve();
    };
    img.onerror = (error) => {
      console.error('封面图片预加载失败:', error);
      resolve(); // 即使失败也resolve，避免阻塞流程
    };
    img.src = url;
  });
};

// 修改提交逻辑，在发布成功后预加载封面
const submitForm = async () => {
  try {
    isSubmitting.value = true;
    
    // 表单验证
    if (!form.title || !form.author || !form.categoryId || !form.price || !form.description) {
      ElMessage.error('请填写所有必填项');
      isSubmitting.value = false;
      return;
    }
    
    // 编辑模式下，如果不上传新封面，则不需要验证封面
    if (!isEditMode.value && !form.cover) {
      ElMessage.error('请上传书籍封面');
      isSubmitting.value = false;
      return;
    }
    
    // 获取分类名称
    const category = categories.value.find(c => c.id === form.categoryId);
    if (!category) {
      ElMessage.error('无效的分类选择');
      isSubmitting.value = false;
      return;
    }
    
    if (isEditMode.value) {
      // 编辑模式: 准备要更新的数据
      const updateData = {
        book_id: parseInt(bookId.value),
        title: form.title,
        author: form.author,
        category: category.name,
        price: parseFloat(form.price),
        new_degree: form.newDegree * 10,
        description: form.description
      };
      
      // 如果上传了新封面，添加封面相关字段
      if (form.cover) {
        // 读取封面文件为 base64
        const reader = new FileReader();
        reader.readAsDataURL(form.cover);
        
        reader.onload = async () => {
          try {
            // 获取 base64 编码的图片数据
            const base64Data = reader.result.split(',')[1];
            
            // 获取图片类型
            const coverType = form.cover.type.split('/')[1];
            
            // 添加封面字段
            updateData.cover = base64Data;
            updateData.cover_type = coverType;
            
            // 提交数据
            await submitEditData(updateData);
          } catch (error) {
            console.error('处理封面失败:', error);
            isSubmitting.value = false;
          }
        };
        
        reader.onerror = (error) => {
          console.error('读取图片失败:', error);
          ElMessage.error('读取图片失败');
          isSubmitting.value = false;
        };
      } else {
        // 没有新封面，直接提交数据
        await submitEditData(updateData);
      }
    } else {
      // 新增模式: 处理封面并提交
      // 读取封面文件为 base64
      const reader = new FileReader();
      reader.readAsDataURL(form.cover);
      
      reader.onload = async () => {
        try {
          // 获取 base64 编码的图片数据
          const base64Data = reader.result.split(',')[1];
          
          // 获取图片类型
          const coverType = form.cover.type.split('/')[1];
          
          // 创建书籍数据对象
          const bookData = {
            title: form.title,
            author: form.author,
            category: category.name,
            price: parseFloat(form.price),
            new_degree: form.newDegree * 10,
            description: form.description,
            cover: base64Data,
            cover_type: coverType
          };
          
          // 提交书籍数据
          console.log('提交书籍数据:', {
            ...bookData,
            cover: `${bookData.cover.substring(0, 20)}... (${bookData.cover.length} 字符)`
          });
          
          // 调用API发布书籍
          const response = await api.book.publish(bookData);
          console.log('书籍创建成功:', response);
          
          // 提取书籍ID
          let newBookId = null;
          if (response && response.book_id) {
            newBookId = response.book_id;
          } else if (response && response.id) {
            newBookId = response.id;
          }
          
          // 显示成功消息
          ElMessage.success('书籍发布成功！');
          
          // 如果获取到了新书籍的ID，先预加载封面
          if (newBookId) {
            try {
              console.log('开始预加载新发布书籍的封面, 书籍ID:', newBookId);
              // 等待服务器处理
              await new Promise(resolve => setTimeout(resolve, 500));
              
              // 获取封面URL
              const coverResponse = await api.book.getCover(newBookId);
              
              if (coverResponse) {
                let coverUrl = '';
                if (typeof coverResponse === 'string') {
                  coverUrl = `http://localhost:8080/${coverResponse}`;
                } else if (coverResponse.cover) {
                  coverUrl = `http://localhost:8080/${coverResponse.cover}`;
                }
                
                if (coverUrl) {
                  // 预加载图片
                  await preloadImage(coverUrl);
                }
              }
            } catch (error) {
              console.error('预加载封面失败，仍继续跳转:', error);
            }
          }
          
          // 跳转到我的书籍页面的在售书籍标签页(使用刷新方式)
          window.location.href = '/my-books?tab=selling';
        } catch (error) {
          console.error('发布书籍失败:', error);
          ElMessage.error('发布失败: ' + (error.message || '未知错误'));
          isSubmitting.value = false;
        }
      };
      
      reader.onerror = (error) => {
        console.error('读取图片失败:', error);
        ElMessage.error('读取图片失败');
        isSubmitting.value = false;
      };
    }
  } catch (error) {
    console.error(isEditMode.value ? '编辑书籍失败:' : '发布书籍失败:', error);
    ElMessage.error((isEditMode.value ? '编辑' : '发布') + '失败: ' + (error.message || '未知错误'));
    isSubmitting.value = false;
  }
}

// 提交编辑数据
const submitEditData = async (updateData) => {
  try {
    console.log('提交编辑数据:', {
      ...updateData,
      cover: updateData.cover ? `${updateData.cover.substring(0, 20)}... (${updateData.cover.length} 字符)` : undefined
    })
    
    const response = await api.book.editBook(updateData)
    console.log('书籍编辑成功:', response)
    
    // 显示成功消息并跳转到书籍详情页，添加时间戳参数确保图片刷新
    ElMessage.success('书籍信息已更新！')
    router.push(`/book/${bookId.value}?refresh=${Date.now()}`)
  } catch (error) {
    console.error('编辑书籍失败:', error)
    ElMessage.error('编辑失败: ' + (error.message || '未知错误'))
  } finally {
    isSubmitting.value = false
  }
}

const cancelPublish = () => {
  const confirmed = confirm('确定要取消发布吗？已填写的内容将丢失！')
  if (confirmed) {
    window.location.href = '/my-books?tab=selling';
  }
}
</script>

<style scoped>
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  font-size: 1.8rem;
  color: #1f2937;
  margin-bottom: 0.5rem;
}

.subtitle {
  color: #6b7280;
  margin-bottom: 2rem;
}

.publish-form {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.form-section {
  padding: 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.form-section h2 {
  font-size: 1.2rem;
  color: #374151;
  margin-bottom: 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #374151;
}

.required {
  color: #ef4444;
}

input[type="text"],
input[type="number"],
input[type="tel"],
select,
textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 1rem;
}

input:focus,
select:focus,
textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.condition-slider {
  margin-top: 0.5rem;
}

.condition-slider input[type="range"] {
  width: 100%;
  margin-bottom: 0.5rem;
}

.slider-labels {
  display: flex;
  justify-content: space-between;
  color: #6b7280;
  font-size: 0.9rem;
}

.upload-area {
  border: 2px dashed #d1d5db;
  border-radius: 4px;
  padding: 2rem;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.2s;
}

.upload-area:hover {
  border-color: #3b82f6;
}

.upload-placeholder {
  color: #6b7280;
}

.upload-icon {
  font-size: 2rem;
  display: block;
  margin-bottom: 0.5rem;
  color: #9ca3af;
}

.upload-hint {
  font-size: 0.8rem;
  margin-top: 0.5rem;
}

.preview-container {
  position: relative;
}

.image-preview {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
}

.remove-image {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0.25rem 0.5rem;
  cursor: pointer;
}

.form-actions {
  padding: 1.5rem;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.btn-cancel,
.btn-submit {
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-cancel {
  background-color: #f3f4f6;
  color: #4b5563;
  border: none;
}

.btn-cancel:hover {
  background-color: #e5e7eb;
}

.btn-submit {
  background-color: #3b82f6;
  color: white;
  border: none;
}

.btn-submit:hover:not(:disabled) {
  background-color: #2563eb;
}

.btn-submit:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}
</style> 